import Vue from 'vue'
import axios from 'axios';

const defaultOpt = {
  autoAlert: true, // 请求出错自动弹窗
  returnAll: false, // 请求成功返回所有数据而不只是result
}

const api = {
  initOpt() {
    let opt = { autoAlert: true, returnAll: false, }
    Object.assign(defaultOpt, opt);
  },
  async download(url) {
    try {
      let $http = axios.create({
        baseURL: Vue.prototype.$baseUrl,
        timeout: 10000,
        responseType: "blob"
      })
      let res = await $http.get(Vue.prototype.$baseUrl + url);
      return res.data;
    } catch (error) {
      throw new Error(error)
    }


  },
  verifyCode(type = {}) {
    return new Promise((resolve, reject) => {
      Vue.prototype.$http.get('/VerifyCode' + '/' + type.join('/'), { responseType: "blob" }).then((res) => {
        let data = window.URL.createObjectURL(res.data)
        resolve(data);
      }).catch(reject)
    })


  },
  get(url, data = {}, opt = {}) {
    return new Promise((resolve, reject) => {
      this.initOpt();
      opt = Object.assign({}, defaultOpt, opt)

      // 拼接请求参数
      if (data.length) {
        // let query = []
        // for (let i in data) {
        //   query.push(encodeURIComponent(i)+'='+encodeURIComponent(data[i]))
        // }
        // query = query.join('/')
        // url += (url.indexOf('?') !== -1 ? '&' : '?') + query
        data.forEach(element => {
          url += '/' + element;
        });

      }

      Vue.prototype.$http.get(url)
        .then(data => {
          data = data.data
          if (data.code == 200) {
            resolve(opt.returnAll ? data : data.data)
          } else if (data.code == 401 || data.code == 403) {
            Vue.prototype.vm._router.push('/login')
          } else {
            if (opt.autoAlert === true) {
              Vue.prototype.$alert(data.data.msg || data.msg, '错误');
            }
          }
          reject(data.data.content)
        })
        .catch(err => {
          Vue.prototype.$alert('请求接口出错，请稍后再试', '错误')
          reject(err)
        })
    })
  },

  post(url, data = {}, opt = {}) {
    return new Promise((resolve, reject) => {
      this.initOpt();
      opt = Object.assign({}, defaultOpt, opt)
      // console.log(opt)
      Vue.prototype.$http.post(url, data)
        .then(data => {
          //console.log(data);
          data = data.data
          if (data.code == 200) {
            if (opt.autoAlert === true) {
              Vue.prototype.vm.$message({
                message: data.data.data.msg,
                type: 'success'
              })
            }
            resolve(opt.returnAll ? data : data.data)
          } else if (data.code == 401 || data.code == 403) {
            Vue.prototype.vm._router.push('/login')
          } else {
            if (opt.autoAlert === true) {
              Vue.prototype.$alert(data.msg, '错误');
            }
          }
          if (data.data.exception) {
            reject(data.msg)
          }
          reject(data.data.content)
        })
        .catch(err => {
          if (err.response.data.data.msg) {
            Vue.prototype.$message.error(err.response.data.data.msg, '详细')
          } else {
            Vue.prototype.$alert('请求接口出错，请稍后再试', '错误')
          }
          reject(err)
        })
    })
  },

  put(url, data = {}, opt = {}) {
    return new Promise((resolve, reject) => {
      this.initOpt();
      opt = Object.assign({}, defaultOpt, opt)

      Vue.prototype.$http.put(url, data)
        .then(data => {
          data = data.data
          if (data.code == 200) {
            Vue.prototype.vm.$message({
              message: "更新成功",
              type: 'success'
            })
            resolve(opt.returnAll ? data : data.data)
          } else if (data.code == 401 || data.code == 403) {
            Vue.prototype.vm._router.push('/login')
          } else {
            if (opt.autoAlert === true) {
              Vue.prototype.$alert(data.msg, '错误');
            }
          }
          reject(data.data.content)
        })
        .catch(err => {
          Vue.prototype.$alert('请求接口出错，请稍后再试', '错误')
          reject(err)
        })
    })
  },

  delete(url, data = {}, opt = {}) {
    return new Promise((resolve, reject) => {
      this.initOpt();
      opt = Object.assign(defaultOpt, { autoAlert: true, returnAll: true })

      Vue.prototype.$http.delete(url, data)
        .then(data => {
          data = data.data
          Vue.prototype.$openMsg(data)
          if (data.code == 200)
            resolve(opt.returnAll ? data : data.Data)
          else if (data.Code == 10000)
            Vue.prototype.vm._router.push('/login')

          reject(data.data.content)
        })
        .catch(err => {
          Vue.prototype.$alert('请求接口出错，请稍后再试', '错误')
          reject(err)
        })
    })
  }

}

export default api

